package top.lidee.common.service.twice.management.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.core.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lidee.common.dto.AccountInfo;
import top.lidee.common.service.MerchantService;
import top.lidee.common.service.StoreService;
import top.lidee.common.service.twice.management.BmsManagerService;
import top.lidee.common.service.twice.management.CheckService;
import top.lidee.common.service.twice.management.MtStoreFilaService;
import top.lidee.framework.result.GlobalCheck;
import top.lidee.framework.result.PageUtils;
import top.lidee.framework.result.ResponseResult;
import top.lidee.repository.mapper.MtGoodsCateMapper;
import top.lidee.repository.mapper.MtStoreMapper;
import top.lidee.repository.mapper.MtUserMapper;
import top.lidee.repository.model.MtMerchant;
import top.lidee.repository.model.MtStore;
import top.lidee.repository.model.MtUser;
import top.lidee.repository.model.twice.pojo.management.MtStoreFilaEntity;
import top.lidee.repository.model.twice.vo.management.SearchAllStatusInfoVo;
import top.lidee.repository.model.twice.vo.management.StoreApplicationVo;
import top.lidee.utils.CopyBean;
import top.lidee.utils.MyCollUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static top.lidee.framework.constant.SupplierInfoConstant.*;
import static top.lidee.framework.constant.UserTypeConstant.USER_STATE_YES;
import static top.lidee.framework.enums.CommonExceptionEnum.NOT_FOUND_HYBSH;
import static top.lidee.utils.MapParamsUtil.getStatus;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/9/24 15:20
 */
@Service
@Slf4j
public class CheckServiceImpl implements CheckService {

    @Autowired
    private StoreService storeService;

    @Autowired
    private MtUserMapper mtUserMapper;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MtGoodsCateMapper mtGoodsCateMapper;

    @Autowired
    private BmsManagerService bmsManagerService;

    @Autowired
    private MtStoreFilaService mtStoreFilaService;


    /**
     * @param params
     * @return com.yufubao.framework.result.ResponseResult
     * @description 分页查询审核成功/待审核/的基本信息
     * @author zhangyiheng
     * @date 2024/9/15 16:16
     */
    @Override
    public ResponseResult searchAllStatusInfo(Map<String, Object> params) {

        //法人/店铺名称/手机号码
//        String key = getKey(params);
        //0待审核1审核通过2审核未通过
        String status = getStatus(params);

        PageUtils page = null;
        List<SearchAllStatusInfoVo> vos = new ArrayList<>();
        if (StrUtil.isNotBlank(status)) {
            switch (status) {
                case WAIT:
                case SUCCESS:
                    //待审核、审核成功
                    page = storeService.searchAllStatusInfo(params);
                    List<MtStore> list = (List<MtStore>) page.getList();
                    if (MyCollUtil.isNotEmpty(list)) {
                        for (MtStore po : list) {
                            SearchAllStatusInfoVo vo = CopyBean.copyBean(po, SearchAllStatusInfoVo.class);
                            //设置用户名和主营分类名/小蜜蜂名/商户名
                            Map<String, String> map = getName(po.getMerchantId(), po.getCateId());
                            vo.setUserName(map.get("userName"));
                            vo.setMerchantName(map.get("merchantName"));
                            vo.setCateName(map.get("categoryName"));

                            vos.add(vo);
                        }
                        page.setList(vos);
                        return ResponseResult.okResultPage("page", page);
                    }
                    break;
                case FAIL:
                    //审核失败
                    page = mtStoreFilaService.searchAllStatusInfo(params);
                    List<MtStoreFilaEntity> list2 = (List<MtStoreFilaEntity>) page.getList();
                    if (MyCollUtil.isNotEmpty(list2)) {
                        for (MtStoreFilaEntity po : list2) {
                            SearchAllStatusInfoVo vo = CopyBean.copyBean(po, SearchAllStatusInfoVo.class);
                            //设置用户名和主营分类名/小蜜蜂名/商户名
                            Map<String, String> map = getName(po.getMerchantId(), po.getCateId());
                            vo.setUserName(map.get("userName"));
                            vo.setMerchantName(map.get("merchantName"));
                            vo.setCateName(map.get("categoryName"));

                            vos.add(vo);
                        }
                        page.setList(vos);
                        return ResponseResult.okResultPage("page", page);
                    }
                    break;
                default:
                    break;
            }
        }
        return ResponseResult.okResultPage("page", page);
    }

    /**
     * @param
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据id查询, 待审核
     * @author zhangyiheng
     * @date 2024/9/24 15:57
     */
    @Override
    public ResponseResult searchWaitPass(Integer storeId) {

        SearchAllStatusInfoVo vo = storeService.searchWaitPass(storeId);
        if (Objects.isNull(vo)) {
            return ResponseResult.errorResult(NOT_FOUND_HYBSH);
        }
        return ResponseResult.okResult(vo);
    }

    /**
     * 用户名、分类名、商户名
     *
     * @param
     * @return
     */
    public Map<String, String> getName(Integer merchantId, Integer categoryId) {

        MtMerchant merchant = merchantService.getById(merchantId);

        String nickname = mtUserMapper.selectOne(Wrappers.<MtUser>lambdaQuery()
                .eq(MtUser::getMerchantId, merchant.getId())).getName();

        String categoryName = mtGoodsCateMapper.selectById(categoryId).getName();

        return ImmutableMap.of(
                "userName", nickname,
                "merchantName", merchant.getName(),
                "categoryName", categoryName);
    }

    /**
     * @param dto
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 店铺审核成功
     * @author zhangyiheng
     * @date 2024/9/25 09:50
     */
    @Override
    @Transactional
    public ResponseResult storeApplicationSuccess(StoreApplicationVo dto, AccountInfo accountInfo) {

        //判断是否是人员或代理
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        //删除审核失败日志
        if (StrUtil.isAllNotBlank(dto.getLicenseName(), dto.getAddress(), dto.getIdCard(), dto.getCreditCode())) {
            mtStoreFilaService.remove(Wrappers.<MtStoreFilaEntity>lambdaQuery()
                    .eq(MtStoreFilaEntity::getLicenseName, dto.getLicenseName())
                    .eq(MtStoreFilaEntity::getAddress, dto.getAddress())
                    .eq(MtStoreFilaEntity::getIdCard, dto.getIdCard())
                    .eq(MtStoreFilaEntity::getCreditCode, dto.getCreditCode()));


            //修改审核状态
            storeService.update(Wrappers.<MtStore>lambdaUpdate()
                    .set(MtStore::getStatus, SUCCESS)
                    .set(MtStore::getOperator, bmsManagerService.getById(managerId).getName())
                    .eq(MtStore::getId, dto.getStoreId())
                    .eq(MtStore::getLicenseName, dto.getLicenseName())
                    .eq(MtStore::getAddress, dto.getAddress())
                    .eq(MtStore::getIdCard, dto.getIdCard())
                    .eq(MtStore::getCreditCode, dto.getCreditCode()));
        }


        return ResponseResult.ok();
    }

    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 店铺审核失败
     * @author zhangyiheng
     * @date 2024/9/24 16:25
     */
    @Override
    @Transactional
    public ResponseResult storeApplicationFila(StoreApplicationVo vo, AccountInfo accountInfo) {
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        MtStore store = storeService.getById(vo.getStoreId());

        //删除店铺相关数据，保存到日志表
        if (StrUtil.isAllNotBlank(vo.getLicenseName(), vo.getAddress(), vo.getIdCard(), vo.getCreditCode())) {

            //加入审核失败表
            MtStoreFilaEntity mtStoreFilaEntity = CopyBean.copyBean(store, MtStoreFilaEntity.class);
            mtStoreFilaEntity.setFailCause(vo.getFailCause());
            mtStoreFilaEntity.setAuditor(managerId);
            mtStoreFilaEntity.setOperator(bmsManagerService.getById(managerId).getName());
            mtStoreFilaService.save(mtStoreFilaEntity);


            storeService.removeById(store.getId());
        }
        return ResponseResult.ok();
    }
}
